﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;


public static class JsonHelper
{
    public static JavaScriptSerializer JSS = new JavaScriptSerializer();

    /// <summary>
    /// 对象转换为Json数据
    /// </summary>
    /// <typeparam name="T">类型</typeparam>
    /// <param name="obj">对象</param>
    /// <returns></returns>
    public static string ToJson<T>(T obj) where T : class
    {
        return JSS.Serialize(obj);
    }

    /// <summary>
    /// Json转换为指定类型对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="json">json字符串</param>
    /// <returns></returns>
    public static T ToObject<T>(string json) where T : class
    {
        return JSS.Deserialize<T>(json);
    }



    /// <summary>
    /// 将json字符串反序列化为对象
    /// </summary>
    /// <typeparam name="T">可序列化对象</typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T JsonToObject<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

    /// <summary>
    /// 将对象序列化为json字符串
    /// </summary>
    /// <param name="obj">可序列化对象</param>
    /// <returns></returns>
    public static string ObjectToJson(object obj)
    {
        string val = String.Empty;
        val = JsonConvert.SerializeObject(obj);
        return val;

    }


    /// <summary>
    /// 将字典转为对象
    /// </summary>
    public static T ToObject<T>(IDictionary<string, object> dict) where T : class
    {
        T model = Activator.CreateInstance<T>();
        PropertyInfo[] modelPro = model.GetType().GetProperties();
        if (modelPro.Length > 0 && dict.Count() > 0)
        {
            for (int i = 0; i < modelPro.Length; i++)
            {
                if (dict.ContainsKey(modelPro[i].Name))
                {
                    object obj = Convert.ChangeType(dict[modelPro[i].Name], modelPro[i].PropertyType);
                    modelPro[i].SetValue(model, obj, null);
                }
            }
        }
        return model;
    }
}
